﻿using BZOrderPrint.BLL.Helper;
using BZOrderPrint.DAL;
using BZOrderPrint.DAL.Entity;

//using BZOrderPrint.PDF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.SS.Formula.Functions;
using static BZOrderPrint.DAL.AppEnum;

namespace BZOrderPrint
{
    public partial class MainForm : Form
    {
        private FrmShop frmShop { get; set; }
        private BZContext context;

        private void Init()
        {
            this.Text = "";
            context = new BZContext(ConfigHelper.ConnString);
            //this.ucMenu1.DataSource = lstMenu;
        }

        public MainForm()
        {
            InitializeComponent();
            Init();

            //PDFHelper.CreatePDF();
            //using (var db = new BZContext(ConfigHelper.ConnString))
            //{
            //    try
            //    {
            //        var dd = db.TestEntities.ToList();
            //        var ss = db.bzShopEntities.ToList();
            //    }
            //    catch (Exception ex)
            //    {
            //    }
            //}
            //FrmTips.ShowTipsError(this, "Error提示信息");
        }

        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
        }

        private void UpdateExcel(string file, int shopId)
        {
            var data = ExcelHelper.ExcelToDataTable("Sheet1", true, file);
            if (data == null && data.Rows.Count == 0) return;
            var list = new List<BzOrderEntity>();
            var orderCodes = new List<string>();
            foreach (DataRow row in data.Rows)
            {
                orderCodes.Add(row["订单号"].ToString());
            }
            if (context.bzOrderEntities.Any(x => orderCodes.Contains(x.OrderCode)))
            {
                MessageBox.Show("不能导入重复的订单数据！");
                return;
            }
            foreach (DataRow row in data.Rows)
            {
                if (!string.IsNullOrEmpty(row["订单号"].ToString()))
                {
                    using (var db = new BZContext(ConfigHelper.ConnString))
                    {
                        var item = new BzOrderEntity
                        {
                            OrderCode = row["订单号"].ToString(),
                            Address = row["地址"].ToString(),
                            CreateTime = DateTime.Now,
                            OrderShopName = row["门店"].ToString(),
                            OrderShopId = shopId,
                            MemberName = row["姓名"].ToString(),
                            MemberNumber = row["会员号"].ToString(),
                            PayType = GetPayType(row["支付方式"].ToString()),
                            OrderStatus = GetOrderStatus(row["状态"].ToString()),
                            OrderType = GetOrderType(row["订单来源"].ToString()),
                            Phone = row["电话"].ToString(),
                            Remark = row["备注"].ToString(),
                            OrderDateTime = string.IsNullOrEmpty(row["日期"].ToString()) ? DateTime.MinValue : DateTime.Parse(row["日期"].ToString()),
                            OrderPrice = double.Parse(row["金额"].ToString()),
                        };
                        var client = new BzClientEntity
                        {
                            ClientNumber = row["会员号"].ToString(),
                            Name = row["姓名"].ToString(),
                            Phone = row["电话"].ToString(),
                            Address = row["地址"].ToString(),
                            CreateTime = DateTime.Now,
                            ShopId = shopId
                        };
                        if (!db.bzClientEntities.Any(x => x.Phone.Equals(client.Phone)))
                        {
                            db.bzClientEntities.Add(client);
                        }
                        db.bzOrderEntities.Add(item);
                        db.SaveChanges();
                        list.Add(item);
                    }
                }
                else
                {
                    using (var db = new BZContext(ConfigHelper.ConnString))
                    {
                        var item = list.LastOrDefault();
                        var itemName = row["商品名称"].ToString();
                        var price = string.IsNullOrEmpty(row["金额"].ToString()) ? 0 : double.Parse(row["金额"].ToString());
                        var quantity = string.IsNullOrEmpty(row["商品数量"].ToString()) || row["商品数量"].ToString().Equals("-") ? 0 : int.Parse(row["商品数量"].ToString().Replace(".00", ""));
                        var reg = new Regex(@"(?is)(?<=\()[^\)]+(?=\))");
                        //var itemCode = reg.Match(itemName.Replace("（", "(").Replace("）", ")"));
                        var itemCode = "";
                        var ma = reg.Match(itemName.Replace("（", "(").Replace("）", ")"));//匹配
                        var r = new Regex(@"([1-9]\d*\.?\d*)|(0\.\d*[1-9])");//正则
                        var regex = new Regex("^[0-9]*$");
                        while (ma.Success)
                        {
                            var str = ma.Groups[0].Value;
                            var m = r.Match(str);//匹配
                            while (m.Success)
                            {
                                if (regex.IsMatch(itemCode)) //利用正则表达式判断是否输入的是数
                                {
                                    itemCode = m.Groups[0].Value;
                                }
                                m = m.NextMatch();//匹配下一个
                            }
                            ma = ma.NextMatch();//匹配下一个
                        }

                        if (!itemName.Contains("配送方式") && !itemName.Contains("运费"))
                        {
                            var orderItem = new BzOrderItemEntity
                            {
                                OrderId = item.Id,
                                Price = price,
                                OrderItem = itemName.Replace($"（{itemCode}）", ""),
                                Quantity = quantity,
                                OrderItemCode = itemCode,
                                CreateTime = DateTime.Now
                            };
                            db.bzOrderItemEntities.Add(orderItem);
                            db.SaveChanges();
                        }
                    }
                }
            }
            MessageBox.Show("导入完成");
        }

        private int GetPayType(string name)
        {
            foreach (int payType in Enum.GetValues(typeof(AppEnum.PayType)))
            {
                var strName = Enum.GetName(typeof(AppEnum.PayType), payType);//获取名称
                if (strName.Equals(name))
                {
                    return (int)payType;
                }
            }
            return 0;
        }

        private int GetOrderStatus(string name)
        {
            foreach (int payType in Enum.GetValues(typeof(AppEnum.PayType)))
            {
                var strName = Enum.GetName(typeof(AppEnum.PayType), payType);//获取名称
                if (strName.Equals(name))
                {
                    return (int)payType;
                }
            }
            return 0;
        }

        private int GetOrderType(string name)
        {
            foreach (int payType in Enum.GetValues(typeof(AppEnum.PayType)))
            {
                var strName = Enum.GetName(typeof(AppEnum.PayType), payType);//获取名称
                if (strName.Equals(name))
                {
                    return (int)payType;
                }
            }
            return 0;
        }

        private void ucMenu1_Load(object sender, EventArgs e)
        {
        }

        private void ShowOrder()
        {
            this.IsMdiContainer = true;//设置父窗体是容器
            OrderForm mySon = new OrderForm
            {
                //MdiParent = this,//设置窗体的父子关系
                //Parent = MainPanel//设置子窗体的容器为父窗体中的Panel
            };//实例化子窗体
            mySon.Show();
        }

        private void ShowShop()
        {
            //this.IsMdiContainer = true;//设置父窗体是容器
            FrmShopManage frm = new FrmShopManage
            {
                //MdiParent = this,//设置窗体的父子关系
                //Parent = MainPanel,//设置子窗体的容器为父窗体中的Panel
                //FormBorderStyle = FormBorderStyle.None, // 无边框
                //TopLevel = false // 不是最顶层窗体
            };//实例化子窗体
            //MainPanel.Controls.Add(frm);
            frm.Show();
        }

        private void UpdateExcel(int type)
        {
            frmShop = new FrmShop();
            var result = frmShop.ShowDialog();
            if (result != System.Windows.Forms.DialogResult.OK) return;
            var fileDialog = new OpenFileDialog
            {
                Multiselect = true,
                Title = "请选择文件",
                Filter = "所有文件(*xls*)|*.xls*" //设置要选择的文件的类型
            };

            if (fileDialog.ShowDialog() != DialogResult.OK) return;
            var file = fileDialog.FileName;//返回文件的完整路径
            if (type.Equals(0))
            {
                UpdateExcel(file, frmShop.SelShopID);
            }
            else
            {
                UpdateExcelGroup(file, frmShop.SelShopID);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
        }

        private void MainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowOrder();
        }

        private void SettingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Export();
        }

        private void ImportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateExcel(0);
        }

        private void StoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowShop();
        }

        private void Export()
        {
            var data = new DataTable();
            var dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "订单号",
                DefaultValue = ""
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "姓名",
                DefaultValue = ""
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "电话",
                DefaultValue = ""
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "数量",
                DefaultValue = ""
            };
            data.Columns.Add(dc);
            dc = new DataColumn()
            {
                DataType = Type.GetType("System.String"),
                ColumnName = "取货登记",
                DefaultValue = ""
            };
            data.Columns.Add(dc);
            var dataTableRow = data.NewRow();
            dataTableRow["订单号"] = "1";
            dataTableRow["姓名"] = "1";
            dataTableRow["电话"] = "1";
            dataTableRow["数量"] = "1";
            dataTableRow["取货登记"] = "1";
            data.Rows.Add(dataTableRow);

            var extHeaders = new List<List<string>>();
            extHeaders.Add(new List<string>()
            {
                ""
            });
            extHeaders.Add(new List<string>()
            {
                ""
            });
            extHeaders.Add(new List<string>()
            {
                "",
                "",
                "门店："
            });
            extHeaders.Add(new List<string>()
            {
                "",
                "",
                "匹配网点：（线路+网点）"
            });

            var cellRangeAddresses = new List<CellRangeAddress>()
            {
                new CellRangeAddress(2, 2, 2, 6),
                new CellRangeAddress(3, 3, 2, 6)
            };

            ExcelHelper.GridToExcelByNPOIMultiHeader(data, @"C:\Users\cairongzhi\Documents\bzorder-print\test.xlsx", extHeaders, cellRangeAddresses);
        }

        private void 导入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateExcel((int)GroupType.ShopOrder);
        }

        private void 导入团购订单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateExcel((int)GroupType.TeamOrder);
        }

        private void UpdateExcelGroup(string file, int shopId)
        {
            var sheeps = ExcelHelper.GetExcelSheetNames(file);
            var orderCodes = new List<string>();
            var itemCode = "";
            var orderId = "";
            foreach (var sheep in sheeps.Where(x => !x.Contains("收货单") && !x.Contains("出货单")))
            {
                orderCodes.AddRange(GetExcelToTeamOrder(file, sheep));
            }
            if (context.teamOrderItemEntities.Any(x => orderCodes.Contains(x.TeamItemCode)))
            {
                MessageBox.Show("不能导入重复的订单数据！");
                return;
            }
            foreach (var sheep in sheeps)
            {
                if (sheep.Contains("收货单"))
                {
                    itemCode = ExcelToOrder(shopId, file, sheep, out orderId);
                }
                if (!sheep.Contains("收货单") && !sheep.Contains("出货单"))
                {
                    ExcelToTeamOrder(itemCode, file, sheep, orderId);
                }
            }
            MessageBox.Show("导入完成");
        }

        private void ExcelToTeamOrder(string itemCode, string fileName, string sheetName, string orderId)
        {
            try
            {
                ISheet sheet = null;
                IWorkbook workbook = null;
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0 || fileName.IndexOf(".xlsm") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }

                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(3);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = 4; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　
                        var order = new TeamOrderItemEntity
                        {
                            BzOrderId = orderId,
                            MemberName = row.GetCell(2).ToString(),
                            Phone = row.GetCell(3).ToString(),
                            ItemName = row.GetCell(4).ToString(),
                            Quantity = int.Parse(row.GetCell(5).ToString().Replace(".00", "")),
                            BzItemCodo = itemCode,
                            TeamItemCode = row.GetCell(1).ToString()
                        };
                        using (var db = new BZContext(ConfigHelper.ConnString))
                        {
                            db.teamOrderItemEntities.Add(order);
                            db.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message);
                return;
            }
        }

        private List<string> GetExcelToTeamOrder(string fileName, string sheetName)
        {
            ISheet sheet = null;
            IWorkbook workbook = null;
            var orderCodes = new List<string>();
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            if (fileName.IndexOf(".xlsx") > 0 || fileName.IndexOf(".xlsm") > 0) // 2007版本
                workbook = new XSSFWorkbook(fs);
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook(fs);

            if (sheetName != null)
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet == null) return null;

            // 最后一列的标号
            int rowCount = sheet.LastRowNum;
            for (int i = 2; i <= rowCount; ++i)
            {
                IRow row = sheet.GetRow(i);
                if (row == null) continue; //没有数据的行默认是null　　
                if (i >= 4)
                {
                    orderCodes.Add(row.GetCell(1).ToString());
                }
            }
            return orderCodes;
        }

        private string ExcelToOrder(int shopId, string fileName, string sheetName, out string orderId)
        {
            var itemCode = "";
            orderId = CreateOrderId();
            try
            {
                ISheet sheet = null;
                IWorkbook workbook = null;
                var order = new BzOrderEntity
                {
                    OrderCode = orderId,
                    OrderShopId = shopId,
                    OrderDateTime = DateTime.Now,
                    OrderShopName = frmShop.Shops.FirstOrDefault(x => x.Key.Equals(shopId)).Value ?? "",
                    CreateTime = DateTime.Now,
                    IsGroup = 1
                };
                var orderItems = new List<BzOrderItemEntity>();

                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0 || fileName.IndexOf(".xlsm") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }

                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(1);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string value = cell.StringCellValue.Replace(" ", "").Replace("?", "");
                            if (value != null)
                            {
                                if (i == 1)
                                {
                                    order.MemberName = value;
                                }

                                if (i == 3)
                                {
                                    order.Phone = value;
                                }
                            }
                        }
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = 2; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null)
                            {
                                //同理，没有数据的单元格都默认是null
                                string value = row.GetCell(j).ToString();
                                if (i == 2 && j == 1)
                                {
                                    order.Address = value;
                                }

                                if (i == 2 && j == 2)
                                {
                                    order.MemberNumber = value;
                                }
                            }
                        }

                        if (i == 5)
                        {
                            using (var db = new BZContext(ConfigHelper.ConnString))
                            {
                                db.bzOrderEntities.Add(order);
                                db.SaveChanges();
                            }

                            orderItems.Add(new BzOrderItemEntity
                            {
                                OrderId = order.Id,
                                OrderItemCode = row.GetCell(0).ToString(),
                                OrderItem = row.GetCell(1).ToString(),
                                Quantity = int.Parse(row.GetCell(2).ToString().Replace(".00", ""))
                            });

                            itemCode = row.GetCell(0).ToString();
                        }

                        if (cellCount > 7)
                        {
                            if (i > 5 && i < (rowCount - 1))
                            {
                                orderItems.Add(new BzOrderItemEntity
                                {
                                    OrderId = order.Id,
                                    OrderItemCode = row.GetCell(0).ToString(),
                                    OrderItem = row.GetCell(1).ToString(),
                                    Quantity = int.Parse(row.GetCell(2).ToString().Replace(".00", ""))
                                });
                            }
                        }
                    }

                    using (var db = new BZContext(ConfigHelper.ConnString))
                    {
                        db.bzOrderItemEntities.AddRange(orderItems);
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message);
                return "";
            }
            return itemCode;
        }

        private string CreateOrderId()
        {
            var dataTime = DateTime.Now;
            var r1 = new Random();
            var a1 = r1.Next(1, 100);
            return dataTime.ToFileTime() + a1.ToString("000");
        }

        private void WhloeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var whole = new WhloeOrderForm();
            whole.Show();
        }

        private void 设置默认打印机ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frmSetDefaultPrinter = new FrmSetPrinter();
            frmSetDefaultPrinter.Show();
        }

        private void 客户管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frmClientManage = new FrmClientManage();
            frmClientManage.Show();
        }
    }
}